# -*- coding: utf-8 -*-

import logging
import os


rootLogger = logging.getLogger()
rootLogger.setLevel(logging.INFO)

test_log_formatter = logging.Formatter(
    "[%(asctime)s]"
    "[%(filename)s:%(lineno)d]"
    "[client_ip:%(ip)s][command:%(api_command)s]"
    "[%(levelname)s][%(message)s]"
)

os.environ['proc_module'] = 'test'
os.environ['proc_identify'] = '0'


class TestFilter(logging.Filter):
    def filter(self, record):
        record.ip = '127.0.0.1'
        record.api_command = 'Test'
        return True


def add_file_log_handle():
    import os
    from logging.handlers import TimedRotatingFileHandler
    from conf import LOG_CFG
    module = os.environ.get('proc_module', '')
    identify = os.environ.get('proc_identify', '')  # or os.getpid()

    if module:
        # service module
        log_path = os.path.normpath(os.path.join(
            os.path.dirname(__file__),
            LOG_CFG['path'],
            LOG_CFG['prefix'] + '_' + str(module) + '_' + str(identify) + '.log'
        ))
        log_formatter = test_log_formatter
    else:
        # no module
        try:
            # uwsgi api
            import uwsgi
            worker_id = uwsgi.worker_id()
            log_path = os.path.normpath(os.path.join(
                os.path.dirname(__file__),
                LOG_CFG['path'],
                LOG_CFG['prefix'] + str(worker_id) + '.log'
            ))
        except ImportError:
            # non uwsgi
            log_path = os.path.normpath(os.path.join(
                os.path.dirname(__file__),
                LOG_CFG['path'],
                LOG_CFG['prefix'] + '.log'
            ))
        log_formatter = test_log_formatter

    f = TestFilter()
    file_handler = TimedRotatingFileHandler(log_path, when='midnight', backupCount=20,  encoding='utf-8')
    file_handler.addFilter(f)
    file_handler.setFormatter(log_formatter)
    rootLogger.addHandler(file_handler)


def add_stream_log_handle():
    console_handler = logging.StreamHandler()
    f = TestFilter()
    console_handler.addFilter(f)
    console_handler.setFormatter(test_log_formatter)
    rootLogger.addHandler(console_handler)


add_file_log_handle()

if os.environ.get('DISABLE_STDOUT') != 'true':
    add_stream_log_handle()
